from distutils.log import error
import os
import IUtils

# cconbPip管线
cconbPip = '''
  //新加一个额外处理cconb的资源管道
  function append_cconb_convert_pip() {
    const assetManager = cc.assetManager;
    //新建一个额外处理cconb的资源管道
    assetManager.transformPipeline.append(function (task) {
      const input = task.output = task.input;
      for (let item of input) {
        if (!item.url) continue;
        //更改资源依赖
        item.url.endsWith(".cconb") && ( item.url = cc.path.changeExtname(item.url, ".cconb.bin") );
      }
    });
    //重写bin资源加载处理
    assetManager.downloader.register("bin", (url, options, onComplete) => {
      url.endsWith(".cconb.bin") ? assetManager.downloader._downloaders[".cconb"]() : assetManager.downloader._downloaders[".bin"]();
    })
  }
'''

# 转换cconb格式 to bin
def ConvertConb2bin(dir):
    for root, dirs, files in os.walk(dir):
        path = root.replace('\\', '/')
        for f in files:
            url = '%s/%s' % (path, f)
            info = os.path.splitext(f)
            name = info[0]
            ext = info[1]
            if ext == ".cconb":
                os.rename(f"{root}/{f}", f"{root}/{name}.cconb.bin")
                print(f"{root}/{name}.cconb.bin")

# 注入脚本到项目中
def intoApplication(dir):
    content = IUtils.fromFile(f"{dir}/application.js")
    content = content.replace(
        "function topLevelImport(url) {", "%s\n\tfunction topLevelImport(url) {" % cconbPip, 1)
    content = content.replace("return loadAssetBundle(settings.hasResourcesBundle, settings.hasStartSceneBundle);",
                              "append_cconb_convert_pip();//创建cconb管道\n\treturn loadAssetBundle(settings.hasResourcesBundle, settings.hasStartSceneBundle);", 1)
    IUtils.writeInFile(f"{dir}/application.js",content)

# 入口
if __name__ == "__main__":

    web_mobileUrl = "./src/web-mobile"

    if not os.path.exists(web_mobileUrl):
        error("请将cocos打包后的 web-mobile文件夹 放入 src目录下")
    else:
        ConvertConb2bin(f"{web_mobileUrl}/assets")
        intoApplication(web_mobileUrl)
